package ubadb.bench;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Set;

import ubadb.bench.tests.Test;
import ubadb.bench.tests.TestResult;
import ubadb.bench.util.PageReferenceTraceGenerator;
import ubadb.bench.util.TraceUtil;
import ubadb.external.bufferManagement.etc.PageReferenceTrace;

public class SingleBufferCompare {
	public static void main(String[] args) {
		try {
			new SingleBufferCompare().run(args);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static final PageReferenceTrace TRACE_SMALL = TraceUtil
			.generateRandomTrace(100, 3);

	private static final PageReferenceTrace TRACE_BIG = TraceUtil
			.generateRandomTrace(1000, 15);

	private static final PageReferenceTrace TRACE_BNLJ_BIG = new PageReferenceTraceGenerator()
			.generateBNLJ("A", 400, "B", 500, 100);

	private static final PageReferenceTrace TRACE_BNLJ_SMALL = new PageReferenceTraceGenerator()
			.generateBNLJ("A", 40, "B", 50, 10);

	private static final Test[] TESTS = new Test[] {
	//
			new Test("BNLJ SMALL", TRACE_BNLJ_SMALL),
			//
			new Test("BNLJ BIG", TRACE_BNLJ_BIG),
			//
			new Test("SMALL", TRACE_SMALL),
			//
			new Test("BIG", TRACE_BIG) };

	void run(String args[]) throws FileNotFoundException {
		test(TESTS, SingleBufferTestCase.INSTANCES, "output1-2.csv");
	}

	public static void test(Test[] tests, BufferPoolTestCase[] cases,
			String output) throws FileNotFoundException {
		PrintWriter csv = new PrintWriter(new FileOutputStream(output));
		csv.println("Test,BufferSize,Strategy,Rate");
		for (Test test : tests) {
			Set<Integer> bufferSizes = test.getBuffersSizes(11);
			System.out.println("Testing \"" + test.getName() + "\" with "
					+ test.getTables().size() + " tables and "
					+ test.getTrace().getPageReferences().size()
					+ " calls. Buffers: " + bufferSizes);
			for (Integer bufferSize : bufferSizes) {
				System.out.println("   BufferSize: " + bufferSize);
				for (BufferPoolTestCase testCase : cases) {
					System.out.print("       Case: " + testCase.getName());
					long init = System.currentTimeMillis();
					TestResult result = test.test(testCase, bufferSize);
					if (result == null) {
						System.out.println(". Skipped");
					} else {
						System.out.println(". Result: " + result + " ("
								+ (System.currentTimeMillis() - init) + "ms)");

						csv.println("\"" + test.getName() + "\"," + bufferSize
								+ "," + testCase.getName() + ","
								+ result.hitRate());
					}
				}
			}
			csv.flush();
			System.out.println();
		}
		csv.flush();
		csv.close();
	}

}
